extends Node

@onready var main_menu = $UI/MainMenu
@onready var debug_info = $UI/DebugInfo
@onready var address_entry = $UI/MainMenu/MarginContainer/VBoxContainer/HBoxContainer/AddressEntry
@onready var upnp_checkbox = $UI/MainMenu/MarginContainer/VBoxContainer/HBoxContainer/UpnpCheckbox

const Player = preload("res://Scenes/tank/Tank.tscn")
const health_box = preload("res://Scenes/healing_box.tscn")
const damage_box = preload("res://Scenes/damage_box.tscn")

const PORT = 9999
var enet_peer = ENetMultiplayerPeer.new()
var rng = RandomNumberGenerator.new()
var spawn_health_box = true

var players = []

func _unhandled_input(event):
	if Input.is_action_just_pressed("quit"):
		get_tree().quit()
	if Input.is_action_just_pressed("debug_info"):
		debug_info.visible = !debug_info.visible

func add_player(peer_id):
	var player = Player.instantiate()
	player.name = str(peer_id)
	if $UI/MainMenu/MarginContainer/VBoxContainer/NickEdit.text != '' :
		player.nick_name = $UI/MainMenu/MarginContainer/VBoxContainer/NickEdit.text
	else: 
		player.nick_name = 'Player_' + str(peer_id)
	add_child(player)
	$UI/DebugInfo/DebugInfo/VBoxContainer/ID.text = str(peer_id)
	players.append(player)

func remove_player(peer_id):
	var player = get_node_or_null(str(peer_id))
	if player:
		player.queue_free()

func _on_host_button_pressed():
	main_menu.hide()
	
	enet_peer.create_server(PORT)
	multiplayer.multiplayer_peer = enet_peer
	multiplayer.peer_connected.connect(add_player)
	multiplayer.peer_disconnected.connect(remove_player)
	
	add_player(multiplayer.get_unique_id())
	
	if upnp_checkbox.button_pressed:
		upnp_setup()

func _on_join_button_pressed():
	main_menu.hide()
	
	if upnp_checkbox.button_pressed:
		enet_peer.create_client(address_entry.text, PORT)
		multiplayer.multiplayer_peer = enet_peer
	else:
		enet_peer.create_client("localhost", PORT)
		multiplayer.multiplayer_peer = enet_peer

func upnp_setup():
	var upnp = UPNP.new()
	
	var discover_result = upnp.discover()
	assert(discover_result == UPNP.UPNP_RESULT_SUCCESS, "UPNP Discover Failed! Error %s" % discover_result)
	
	assert(upnp.get_gateway() and upnp.get_gateway().is_valid_gateway(), "UPNP Invalid Gateway")
	
	var map_result = upnp.add_port_mapping(PORT)
	assert(map_result == UPNP.UPNP_RESULT_SUCCESS, "UPNP Port Mapping Failed! Error %s" % map_result)
	
	print("Success! Join Address: %s" % upnp.query_external_address())

@rpc("any_peer")
func spawn_box():
	var box
	if spawn_health_box:
		box = health_box.instantiate()
		spawn_health_box = false
	else:
		box = damage_box.instantiate()
		spawn_health_box = true
	box.position = Vector3(rng.randf_range(-39.0, 31.0), 10, rng.randf_range(-35.0, 35.0))
	box.name = str(rng.randf_range(0, 10.0))
	
	add_child(box)

func _on_timer_timeout():
	if not is_multiplayer_authority():
		spawn_box.rpc()
